//
//  CommonSectionComponent.swift
//  ClockWidget
//
//  Created by TSYH on 2023/10/17.
//

import UIKit

public class CommonSectionComponent: CollectionViewSectionComponent {
    var cellComponents: [CollectionViewCellComponent]
    var header: CollectionViewReuseViewComponent?
    var footer: CollectionViewReuseViewComponent?
    public var inset: UIEdgeInsets
    public var rowSpacing: CGFloat
    public var columnSpacing: CGFloat
    
    public init(cellComponents: [CollectionViewCellComponent],
         header: CollectionViewReuseViewComponent? = nil,
         footer: CollectionViewReuseViewComponent? = nil,
         inset: UIEdgeInsets = .zero,
         rowSpacing: CGFloat = 10.0,
         columnSpacing: CGFloat = 10.0) {
        self.cellComponents = cellComponents
        self.header = header
        self.footer = footer
        self.inset = inset
        self.rowSpacing = rowSpacing
        self.columnSpacing = columnSpacing
    }
    
    public var cells: [CollectionViewCellComponent] {
        return cellComponents
    }
    
    public var headerComponent: CollectionViewReuseViewComponent? {
        return header
    }
    
    public var footerComponent: CollectionViewReuseViewComponent? {
        return footer
    }
   
    public var sectionInset: UIEdgeInsets {
        return inset
    }
    
    public var lineSpacing: CGFloat {
        return rowSpacing
    }
    
    public var itemSpacing: CGFloat {
        return columnSpacing
    }
    
    public func clear() {
        header = nil
        footer = nil
        cellComponents.removeAll()
    }
    
    public func append(_ childrens: [Component]) {
        if let header = childrens.first(where: { ($0 as? CollectionViewReuseViewComponent)?.viewType == .header }) as? CollectionViewReuseViewComponent {
            self.header = header
        }
        if let footer = childrens.first(where: { ($0 as? CollectionViewReuseViewComponent)?.viewType == .footer }) as? CollectionViewReuseViewComponent {
            self.footer = footer
        }
        let cells = childrens.filter({  $0 is CollectionViewCellComponent }) as? [CollectionViewCellComponent]
        self.cellComponents.append(contentsOf: cells ?? [])
    }
    
    public func remove(_ viewType: CollectionViewReuseViewType) {
        if viewType == .header {
            self.header = nil
        }
        if viewType == .footer {
            self.footer = nil
        }
    }
}
